//
//  LockViewController.m
//  ProjectforHDX
//
//  Created by H.DX on 16/3/10.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "LockViewController.h"
//指纹锁
#import "WJTouchID.h"

#import "DrawLockView.h"

#define KSCREENW [UIScreen mainScreen].bounds.size.width

#define KSCREENH [UIScreen mainScreen].bounds.size.height

@interface LockViewController ()<DrawLockViewDelegate,WJTouchIDDelegate,UIAlertViewDelegate>

@property(nonatomic,weak)UILabel *unlocklabel;//顶部按钮

@property(nonatomic,weak)UILabel *setpassword;//顶部按钮
//标记是否是重置密码
@property(nonatomic ,assign,getter=isresetpassword)BOOL resetpassword;
//判断是否是两次确认密码
@property(nonatomic,assign,getter=istwopassword)BOOL twopassword;
@property(weak,nonatomic)DrawLockView *lockview;
//底部按钮
@property(nonatomic,weak)UIButton *setbottomBtn;

//标记是否是重置密码好事下次设置
@property(nonatomic ,assign)BOOL isreset;




#pragma mark 指纹解锁

@property (strong, nonatomic)   UIView *WJTouchView;//背景


@property (strong, nonatomic)   UILabel *Notice;

@property (nonatomic, strong) WJTouchID *touchID;


@end

@implementation LockViewController


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //掩藏导航栏
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:animated];
    
    
}
-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"HomeButtomBG"]];
    
    //手势解锁
    self.resetpassword = NO;
    self.twopassword = NO;
    DrawLockView *lockview = [[DrawLockView alloc]init];
    
    lockview.backgroundColor = [UIColor clearColor];
    lockview.width = 300;
    lockview.height = 300;
    lockview.left = (KSCREENW - lockview.width) * 0.5;
    lockview.top= 150;
    self.lockview = lockview;
    lockview.delegate = self;
    [self.view addSubview:lockview];
    self.lockview.delegate = self;
    [self judgeMentLocalPassWord];
    

    
     dispatch_async(dispatch_get_main_queue(), ^{
     
         [self addTouchView];
         
         [self initWJTouch];
     
     });
    
    

    
 
    

}

-(void)remoWJTouchView{
    
    [self.WJTouchView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.WJTouchView removeFromSuperview];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(alertView.tag==9998){
    if ([alertView cancelButtonIndex] != buttonIndex) {
      
        [self remoWJTouchView];
 
    }
    else{
      
        [self initWJTouch];
    }
    }
    
    
}
#pragma mark 手势解锁
//添加重置密码按钮
- (void)addResetPassWordBuutton{
    UIButton *resetpassword = [[UIButton alloc]init];
    self.setbottomBtn=resetpassword;
    if(self.isreset){
    [resetpassword setTitle:@"重置密码" forState:UIControlStateNormal];
    }
    else{
    [resetpassword setTitle:@"下次设置" forState:UIControlStateNormal];
    }
    [resetpassword setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [resetpassword sizeToFit];
    resetpassword.top= self.lockview.bottom + 40;
    resetpassword.left = (KSCREENW - resetpassword.width) * 0.5;
    [self.view addSubview:resetpassword];
    [resetpassword addTarget:self action:@selector(ButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
}




//取消设置按钮
- (void)ButtonClick{
 
    if(self.isreset){
        self.resetpassword=YES;
        [self.setbottomBtn setTitle:@"重置密码" forState:UIControlStateNormal ];
        [self setLocklabel:@"确认旧手势密码"];
        [self.unlocklabel sizeToFit];
 
        
    }
    else{
       [self.setbottomBtn setTitle:@"下次设置" forState:UIControlStateNormal ];
        
        if(self.lockdegateleblock){
            self.lockdegateleblock(0,[NSDictionary dictionaryWithObjectsAndKeys:@"0",@"code",@"取消设置",@"msg", nil]);
        }
    }
}


//lockview的代理方法
- (BOOL)unlockView:(DrawLockView *)unlockView withPassword:(NSString *)password
{
    NSString *localpasswordone = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordone"];
    NSString *localpasswordtwo = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordtwo"];
    
    if (self.twopassword) {
        if ([localpasswordone isEqualToString:localpasswordtwo]) {
            UIAlertView *confirmalertview = [[UIAlertView alloc]initWithTitle:@"密码设置成功" message:@"请输入密码解锁" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [confirmalertview show];
            self.isreset=YES;
            [self.setbottomBtn setTitle:@"重置密码" forState:UIControlStateNormal];
            
            [self setLocklabel:@"手势解锁"];
            self.twopassword = NO;
            return YES;
        }
        
        else
        {
            UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"与上次密码不对应" message:@"请重新设置密码" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alertview show];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"passwordone"];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"passwordtwo"];
            self.isreset=YES;
            [self.setbottomBtn setTitle:@"重置密码" forState:UIControlStateNormal];
            
            [self setLocklabel:@"设置密码"];
               self.resetpassword=NO;
            return NO;
        }
    }
    
    else
        
    {
        if ([password isEqualToString:localpasswordone]) {
            if (self.isresetpassword) {
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"passwordone"];
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"passwordtwo"];
                self.isreset=NO;
                [self.setbottomBtn setTitle:@"下次设置" forState:UIControlStateNormal];
                
                [self setLocklabel:@"设置新密码"];
//                UIAlertView *resetalertview = [[UIAlertView alloc]initWithTitle:@"密码确认成功" message:@"请重新设置密码" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//                [resetalertview show];
            self.resetpassword=NO;
            }
            else
            {
                
                if(self.lockdegateleblock){
                    self.lockdegateleblock(1,[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"200",@"手势正确",@"msg", nil]);
                }
                
            }
            return YES;
        }
        else {
            return NO;
        }
        return NO;
    }
}

- (void)setPassWordSuccess:(NSString *)tabelname{
    
    NSString *localpasswordone = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordone"];
    NSString *localpasswordtwo = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordywo"];
    if (!localpasswordtwo||!localpasswordone ) {
        self.twopassword = YES;
    }
    self.setbottomBtn.hidden=YES;
    self.setpassword.text = tabelname;
    self.unlocklabel.text = tabelname;
    [self.unlocklabel sizeToFit];
    [self.setpassword sizeToFit];
    self.setpassword.left = (KSCREENW - self.setpassword.width) * 0.5;
    self.setpassword.top = self.lockview.bottom+40;
    self.unlocklabel.left = (KSCREENW - self.unlocklabel.width) * 0.5;
    self.unlocklabel.top = self.lockview.top-40;
    
}

//判断本地是否存有密码
- (void)judgeMentLocalPassWord{
    NSString *password = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordone"];
    if (password == nil) {
        self.isreset=NO;
//        //添加下次设置按钮
        [self addResetPassWordBuutton];
        [self setPassWordView:@"设置手势密码"];
    }else{
        self.isreset=YES;
        //添加重置密码按钮
        [self addResetPassWordBuutton];
        [self unlockView:@"手势解锁"];
    }
    
}

//设置密码界面
- (void)setPassWordView:(NSString *)lockstr{
    UILabel *locklabel = [[UILabel alloc]init];
    locklabel.text = lockstr;
    locklabel.textAlignment = NSTextAlignmentCenter;
    self.setpassword = locklabel;
    locklabel.textColor = [UIColor whiteColor];
    [locklabel sizeToFit];
    locklabel.left = (KSCREENW - locklabel.width) * 0.5;
    locklabel.top = self.lockview.top - 40;
    [self.view addSubview:locklabel];
}

- (void)setLocklabel:(NSString *)locklstr{
    
    self.setpassword.text = locklstr;
    self.unlocklabel.text = locklstr;
    [self.setpassword sizeToFit];
    [self.unlocklabel sizeToFit];
    self.setpassword.left = (KSCREENW - self.setpassword.width) * 0.5;
    self.setpassword.top =self.lockview.bottom+40;
    self.unlocklabel.left= (KSCREENW - self.unlocklabel.width) * 0.5;
    self.unlocklabel.top = self.lockview.top-40;
    [self.view addSubview:self.setpassword];
    [self.view addSubview:self.unlocklabel];
    
}

//手势解锁界面
- (void)unlockView:(NSString *)unlockstr{
    UILabel *locklabel = [[UILabel alloc]init];
    self.unlocklabel = locklabel;
    locklabel.text = unlockstr;
    locklabel.textColor = [UIColor whiteColor];
    [locklabel sizeToFit];
    locklabel.left = (KSCREENW - locklabel.width) * 0.5;
    locklabel.top = self.lockview.top- 40;
    [self.view addSubview:locklabel];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark 指纹解锁

-(void)addTouchView{
    
    self.WJTouchView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    self.WJTouchView.backgroundColor=[UIColor whiteColor];
    
    [self.view addSubview:self.WJTouchView];
 
    UIImage *image=[UIImage imageNamed:@"fingerprint"];
    UIImageView *imgshow=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    imgshow.image=image;
    imgshow.layer.masksToBounds=YES;
    imgshow.clipsToBounds=YES;
    imgshow.contentMode=UIViewContentModeScaleAspectFill;
    
    imgshow.center=self.WJTouchView.center;
    
    self.Notice = [[UILabel alloc]init];
    
    self.Notice.textAlignment = NSTextAlignmentCenter;
    self.Notice.text=@"TouchID验证";
    self.Notice.textColor = [UIColor redColor];
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
    self.Notice.top = imgshow.top- 80;
    
    [self.WJTouchView addSubview: self.Notice];
    
    
    
    [self.WJTouchView addSubview:imgshow];
    
    
}
-(void)initWJTouch{
    
    //指纹解锁
    
    WJTouchID *touchid = [[WJTouchID alloc]init];
    
    [touchid startWJTouchIDWithMessage:WJNotice(@"通过Home健录入解锁指纹", @"The Custom Message") fallbackTitle:WJNotice(@"HDX", @"HDX") delegate:self];
    self.touchID = touchid;
    
 
    

}
- (void)StartWJTouchID {
    
    [self.touchID startWJTouchIDWithMessage:WJNotice(@"这里可以自定义", @"The Custom Message") fallbackTitle:WJNotice(@"按钮标题", @"Fallback Title") delegate:self];
}
/**
 *  TouchID验证成功
 *
 *  (English Comments) Authentication Successul  Authorize Success
 */
- (void) WJTouchIDAuthorizeSuccess {
    self.Notice.text = WJNotice(@"TouchID验证成功", @"Authorize Success");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
    if(self.lockdegateleblock){
        self.lockdegateleblock(1,[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"200",@"手势正确",@"msg", nil]);
    }
}

/**
 *  TouchID验证失败
 *
 *  (English Comments) Authentication Failure
 */
- (void) WJTouchIDAuthorizeFailure {
    self.Notice.text = WJNotice(@"TouchID验证失败", @"Authorize Failure");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
}
/**
 *  取消TouchID验证 (用户点击了取消)
 *
 *  (English Comments) Authentication was canceled by user (e.g. tapped Cancel button).
 */
- (void) WJTouchIDAuthorizeErrorUserCancel {
    
    self.Notice.text = WJNotice(@"取消TouchID验证 (用户点击了取消)", @"Authorize Error User Cancel");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
    
    UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"Touch ID 解锁" message:@"需要验证您的Touch ID" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"使用手势解锁", nil];
    alertview.tag=9998;
    [alertview show];
    
}

/**
 *  在TouchID对话框中点击输入密码按钮
 *
 *  (English Comments) User tapped the fallback button
 */
- (void) WJTouchIDAuthorizeErrorUserFallback {
    self.Notice.text = WJNotice(@"在TouchID对话框中点击输入密码按钮", @"Authorize Error User Fallback ");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
}

/**
 *  在验证的TouchID的过程中被系统取消 例如突然来电话、按了Home键、锁屏...
 *
 *  (English Comments) Authentication was canceled by system (e.g. another application went to foreground).
 */
- (void) WJTouchIDAuthorizeErrorSystemCancel {
    self.Notice.text = WJNotice(@"在验证的TouchID的过程中被系统取消 ", @"Authorize Error System Cancel");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
    
    UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"Touch ID 解锁" message:@"需要验证您的Touch ID" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"使用手势解锁", nil];
    alertview.tag=9998;
    [alertview show];
    
}

/**
 *  无法启用TouchID,设备没有设置密码
 *
 *  (English Comments) Authentication could not start, because passcode is not set on the device.
 */
- (void) WJTouchIDAuthorizeErrorPasscodeNotSet {
    self.Notice.text = WJNotice(@"无法启用TouchID,设备没有设置密码", @"Authorize Error Passcode Not Set");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
    
            [self remoWJTouchView];
    
    
}

/**
 *  设备没有录入TouchID,无法启用TouchID
 *
 *  (English Comments) Authentication could not start, because Touch ID has no enrolled fingers
 */
- (void) WJTouchIDAuthorizeErrorTouchIDNotEnrolled {
    self.Notice.text = WJNotice(@"设备没有录入TouchID,无法启用TouchID", @"Authorize Error TouchID Not Enrolled");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
    
    [self remoWJTouchView];
}

/**
 *  该设备的TouchID无效
 *
 *  (English Comments) Authentication could not start, because Touch ID is not available on the device.
 */
- (void) WJTouchIDAuthorizeErrorTouchIDNotAvailable {
    self.Notice.text = WJNotice(@"该设备的TouchID无效", @"Authorize Error TouchID Not Available");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
            [self remoWJTouchView];
}

/**
 *  多次连续使用Touch ID失败，Touch ID被锁，需要用户输入密码解锁
 *
 *  (English Comments) Authentication was not successful, because there were too many failed Touch ID attempts and Touch ID is now locked. Passcode is required to unlock Touch ID, e.g. evaluating LAPolicyDeviceOwnerAuthenticationWithBiometrics will ask for passcode as a prerequisite.
 *
 */
- (void) WJTouchIDAuthorizeLAErrorTouchIDLockout {
    self.Notice.text = WJNotice(@"多次连续使用Touch ID失败，Touch ID被锁，需要用户输入密码解锁", @"Authorize LAError TouchID Lockout");
 
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
            [self remoWJTouchView];
    
}

/**
 *  当前软件被挂起取消了授权(如突然来了电话,应用进入前台)
 *
 *  (English Comments) Authentication was canceled by application (e.g. invalidate was called while authentication was inprogress).
 *
 */
- (void) WJTouchIDAuthorizeLAErrorAppCancel {
    self.Notice.text = WJNotice(@"当前软件被挂起取消了授权", @"Authorize LAError AppCancel");
 
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
            [self remoWJTouchView];
}

/**
 *  当前软件被挂起取消了授权 (授权过程中,LAContext对象被释)
 *
 *  (English Comments) LAContext passed to this call has been previously invalidated.
 */
- (void) WJTouchIDAuthorizeLAErrorInvalidContext {
    self.Notice.text = WJNotice(@"当前软件被挂起取消了授权", @"Authorize LAError Invalid Context");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
            [self remoWJTouchView];
}
/**
 *  当前设备不支持指纹识别
 *
 *  (English Comments) The current device does not support fingerprint identification
 */
-(void)WJTouchIDIsNotSupport {
    self.Notice.text = WJNotice(@"当前设备不支持指纹识别", @"The Current Device Does Not Support");
    [  self.Notice sizeToFit];
    self.Notice.left = (KSCREENW - self.Notice.width) * 0.5;
            [self remoWJTouchView];
    
}
@end
